package com.andy.retrofitclient;

import android.widget.Toast;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * Created by Andy on 16/7/15.
 */
public class TransformerManager {
    /**
     * 请求过程中的进度条管理，和请求错误管理
     * @param builder
     * @param <T>
     * @return
     */
    public static <T> Observable.Transformer<T, T> progressTransformer(final ResultManager.Builder builder) {
        return new Observable.Transformer<T, T>() {
            @Override
            public Observable<T> call(Observable<T> tObservable) {
                return tObservable
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                if (builder.isShowProgress()) {
                                    builder.getProgressDialog().show();
                                }
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                if (builder.isShowProgress()) {
                                    builder.getProgressDialog().dismiss();
                                }
                            }
                        })
                        .doOnError(new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                //关闭请求进度条
                                if (builder.isShowProgress()) {
                                    builder.getProgressDialog().dismiss();
                                }

                                //显示错误信息
                                if(ResultManager.ErrorTipType.cusDialog==builder.getErrTipType()){
                                    builder.getCusErrDialog().show();
                                }else if(ResultManager.ErrorTipType.toast==builder.getErrTipType()){
                                    Toast.makeText(builder.getContext(),throwable.getMessage(),Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            }
        };
    }
}
